import {assert} from "../../utils/assert";
import sceneManager from "../managers/SceneManager";
import {ScriptRender} from "../../utils/ScriptRender";
import {ModuleBase} from "./ModuleBase";
import jQuery from 'jquery';

class SceneClass extends ModuleBase {

    constructor(clazz = "unknown", interfaceObj = undefined) {
        super(clazz, interfaceObj);
    }

    /**
     * 模块加载的入口
     */
    run(...args) {
        super.run(args);
        //如果当前模块类型为启动器,则需要处理样式库
        super._loadStyleLibrary();
        let deferred = jQuery.Deferred().resolve(), langSet = {};
        //加载语言包,场景配置等信息
        return deferred.then(() => {
            //加载多语言信息
            return super._loadI18nResource(langSet);
        }).then(() => {
            return sceneManager.getConfig(this.metaInfo.name, this);
        }).then((scene) => {
            //当前是启动模块
            return this._launcherScene(scene.config);
        }).then((data) => {
            this.Logger.debug({scene: data.currentScene, lang: langSet});
            return this.$launch({scene: data.currentScene, lang: langSet});
        }).done(() => {
            this.Logger.info("module method launch has been run!");
        });
    }

    destroy() {
        super._releaseStyleLibrary();
        super.destroy();
    }

    //==生命周期方法结束==
    get CurrentApp() {
        return this._app;
    }

    _launcherScene(sceneConfig) {
        assert(this.metaInfo.name === undefined, "property name is null in meta info!");
        let deferred = $.Deferred();
        //由子类实现方法,筛选当前场景
        if (sceneConfig.scene && Array.prototype.isArray(sceneConfig.scene)) {
            //如果对当前应用没有配置, 按照default进行匹配, 反之按照已经配置的应用匹配
            let currentScene = sceneConfig.scene.find((item) => {
                return item.name === this.CurrentApp;
            });
            if (!currentScene && sceneConfig.default) {
                currentScene = sceneConfig.scene.find(item => {
                    return item.name === sceneConfig.default;
                });
            }
            //如果配置中包含Style
            if (currentScene && currentScene.style) {
                //动态加载Style对象
                let url = this._trimSlash() + currentScene.style;
                //如果是没有加载过的Style对象
                if (!ScriptRender.checkStyle(url)) {
                    ScriptRender.addStyle(url);
                }
            }
            //返回当前场景配置
            deferred.resolve({currentScene: currentScene});
        } else {
            console.error("scene config error!!");
            deferred.resolve({currentScene: undefined});
        }
        return deferred.promise();
    }
}

export {SceneClass};